import styles from "./index.module.less";
import showdownHighlight from "showdown-highlight";
import showdown from "showdown";
import "highlight.js/styles/vs2015.css";
import cName from "classnames";
import RecommendationProblem from "../RecommendationProblem";
import {
  useEffect,
  useState,
  useRef,
  useContext,
  useMemo,
  useCallback,
  memo,
  lazy,
  Suspense,
} from "react";
import { IChatItemProps } from "./type";
import { CHAT_ROLE } from "@/utils/chat";
import { IconFont } from "@nutui/icons-react";
import tptLift from "@/assets/chat/tptLift.png";
import supGptCodePlugin from "./plugin";
import { debounce, throttle } from "lodash";
import useCompare from "@/utils/hooks/useCampare";
import { parseString } from "@/utils/common";
import useLoadText from "@/utils/hooks/useLoadText";
import ChatThink from "./think";
import { useGlobalData } from "@/pages/BigScreen/context/chat";
import { render } from "react-dom";
import { ChatContext } from "@/pages/BigScreen/context/store";
import { Recommended } from "@/pages/BigScreen/context/type";
import MsgQuickAction from "../MsgQuickAction";
import TableModel from "@/pages/BigScreen/context/table";
import { Avatar } from "antd";
import { RefreshOutlined } from "@/components/Icons";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";
import "./index.less";

interface FeatureItemType {
  type: ChatFeatureType;
  id: string;
  domId: string;
  content: string;
  renderStr?: string;
}
interface IRenderContentMdProps {
  str: string;
  tablePreview?: string;
  destroyType?: boolean;
}

const hljs = require("highlight.js");
const md = require("markdown-it")({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return (
          '<pre class="hljs"><code>' +
          hljs.highlight(lang, str, true).value +
          "</code></pre>"
        );
      } catch (__) { }
    }

    return (
      '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
    );
  },
});
md.use(supGptCodePlugin);


// 动态导入各类型组件
const componentMap: {
  [key: string]: () => Promise<{ default: React.ComponentType<any> }>;
} = {
  ChatEcharts: () => import("@/components/Chat/components/ChatEcharts"),
  ChatTable: () => import("@/components/Chat/components/ChatTable"),
  ChatRcTable: () => import("@/components/Chat/components/ChatRcTable"),
  ChatAnalysis: () => import("@/components/Chat/components/ChatAnalysis"), // 复用
  ChatRedesign: () => import("@/components/Chat/components/ChatRedesign"),
  ChatSuggested: () => import("@/components/Chat/components/ChatSuggested"),
  ContentSource: () => import("@/components/Chat/components/ContentSource"),
  ChatBI: () => import("@/components/Chat/components/ChatBI"),
  RecommendQues: () => import("@/components/Chat/components/RecommendQues"),
  Suggestions: () => import("@/components/Chat/components/Suggestions"),
  OoopTable: () => import("@/components/Chat/components/OoopTable"),
  ChatPlotly: () => import("@/components/Chat/components/ChatPlotly"),
  ChatThink: () => import("@/components/Chat/components/ChatThink"),
  PidDataTrendEcharts: () =>
    import("@/components/Chat/components/pid/DataTrendEcharts"),
  PidExecuteTrendEcharts: () =>
    import("@/components/Chat/components/pid/ExecuteTrendEcharts"),
  // ChatExam: () => import('@/packageA/components/ChatExam'),
};

function ChatItem(props: IChatItemProps) {
  const {
    key,
    index,
    chatItem,
    mdRenderMode,
    // handleLongPress,
    handleFeedBackDownClick,
  } = props;
  const {
    setCurrentKey,
    setPathJson,
    setAnomalyJson,
    setParamJson,
    setCurrentDevice,
    setCurrentPathDevice,
    chatRef
  } = useContext(BigScreenContext);

  const {
    // theme,
    language,
  } = useGlobalData();
  const {
    qList,
    viewContent,
    isLoading,
    showActionLogList,
    showActionFileList,
    handle,
    updateScrollTop,
    handleActionLogList,
    handleActionFileList,
    resetRecommend,
  } = useContext(ChatContext);

  const { coverImgMap, addTask } = useContext(TableModel);

  // const renderingText = `<div class="chat-answer-load">答案正在生成中...</view>`;
  const renderingText = ` <div class="my-badge my-badge-status">
            <div class="ripple"></div>
            <span class="my-badge-status-text">Think...</span>
          </div>`;
  const renderNoBkText = `未找到相关答案，您可以重新提问`;

  const [renderDom, setRenderDom] = useState<any>(null);
  const converter = new showdown.Converter({
    extensions: [showdownHighlight],
    tables: true,
  });
  const el = useRef<any>(null);
  const anwserRef = useRef<any>(null);

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const longPressRef = useRef<HTMLButtonElement>(null);

  const typedRef = useRef<any>(null);
  const chatItemRef = useRef<any>(null);
  const isLoadingRef = useRef<boolean>(false);
  chatItemRef.current = chatItem;
  isLoadingRef.current = isLoading;
  const featureRef = useRef<FeatureItemType[]>([]);
  const echartsId = useRef<number>(0);

  const [recommendationLoad, setRecommendationLoad] = useState(false);

  const {
    actions,
    tablePreview,
    who,
    role,
    recommended,
    content,
    id,
    msgId,
    loading,
    isInitChat,
    thinks,
    resourceInfo,
  } = useMemo(() => {
    const conInfo = chatItem?.messageBody;
    const contentInfo = conInfo?.contents?.[0];
    const resourceInfo: any =
      contentInfo?.metaData && contentInfo?.metaData?.resource_info
        ? JSON.parse(`${contentInfo?.metaData?.resource_info}`)
        : null;

    // console.log("chatItem.messageBody.thinks", chatItem.messageBody.thinks)
    return {
      actions: chatItem?.messageBody?.actions ?? [],
      // role: chatItem?.messageBody?.contents?.[0]?.role ?? CHAT_ROLE.error,
      who: chatItem?.messageBody?.contents?.[0]?.role ?? CHAT_ROLE.error,
      role: chatItem?.role ?? CHAT_ROLE.error,
      recommended: chatItem?.messageBody?.recommended ?? ({} as Recommended),
      content: chatItem?.messageBody?.contents?.[0]?.content || renderNoBkText,
      parentMsgId: chatItem?.parentMsgId ?? "",
      msgId: chatItem?.msgId ?? "",
      id: chatItem?.id ?? "",
      tablePreview: chatItem?.tablePreview ?? "",
      isInitChat: chatItem?.isInitChat ?? false,
      loading: chatItem.loading,
      thinks: chatItem.messageBody.thinks || [],
      resourceInfo,
    };
  }, [chatItem]);

  const resourceList = useMemo(() => {
    let list: any[] = [];
    if (resourceInfo) {
      list = resourceInfo.resource_list;
    }
    return list;
  }, [resourceInfo]);

  const showRecommendation = useMemo(() => {
    return (
      index === qList?.length - 1 && // 最后一个
      !isInitChat && // 不是 默认的新对话
      !recommendationLoad && // 不在打字状态
      (recommended?.chatId || recommended?.chatId === "") && // 有推荐问题
      !!recommended?.content?.length
    ); // 有推荐问题
  }, [index, qList, isInitChat, recommendationLoad, recommended]);

  const showActionLog = () => {
    // setShowAction(!showAction)
    handleActionLogList(msgId);
  };
  const showActionFile = () => {
    // setShowAction(!showAction)
    handleActionFileList(msgId);
  };
  /**
   * @description: 渲染回答中的文案
   * @param {*} loading 是否为加载中
   * @return {*}
   */
  const renderMd = (loading = true) => {
    let defaultHtml = loading ? renderingText : renderNoBkText;
    if (el?.current) {
      el!.current!.innerHTML = defaultHtml;
    }
  };

  const RenderDynamicComponent = ({ renderType, ...rest }) => {
    const Component = lazy(componentMap[renderType]);

    return (
      <Suspense fallback={<div>Loading...</div>}>
        <Component {...rest} />
      </Suspense>
    );
  };

  const parseMd = (
    mdStr: string
  ): Promise<{
    resultHtml: string;
    featureArr: FeatureItemType[];
  }> => {
    return new Promise((reslove) => {
      // const result = converter.makeHtml(mdStr);
      const result = md.render(mdStr);
      // const result = md.render('<supgptcode data-codeType=bottleneckAnalysis data-codeId=2></supgptcode>');
      const regex = /(<supgptcode\s+[^>]*>[\s\S]*?<\/supgptcode>)/g;
      const arr: FeatureItemType[] = [];
      const replacedString = result.replace(
        regex,
        (match: any, openTag: any, content: any, closeTag: any) => {
          const regexReg =
            /data-codeType=(.*?)\s+data-codeId(?:(?:=(.*?))|\s|>)/;
          const matchReg = match.match(regexReg);
          let dataCodeType = "";
          let dataCodeId = "";

          if (matchReg) {
            dataCodeType = matchReg[1] || "";
            dataCodeId = matchReg[2] || "";
          }
          // 创建一个新的 DOMParser 实例
          const parser = new DOMParser();
          // 解析标签字符串为 DOM 文档
          try {
            const doc = parser?.parseFromString?.(match, "text/html");
            // 获取解析后的标签元素
            const tagElement = doc.body.firstChild as any;
            // 获取标签元素的内容
            const matchText = match.match(
              /<supgptcode[^>]*>([\s\S]*?)<\/supgptcode>/
            );
            const textContent = matchText && matchText[1] ? matchText[1] : "";
            const codeType =
              tagElement?.getAttribute?.("data-codeType") ?? dataCodeType;
            const codeId =
              tagElement?.getAttribute?.("data-codeId") ?? dataCodeId;
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const resId = chatItem.id;
            const idStr = `chat-${codeType}-${chatItem.msgId}-${codeId}`;
            const classStr = `chat-${codeType}-block`;
            arr.push({
              type: codeType,
              id: codeId,
              domId: idStr,
              content: textContent,
            });
            // 在这里根据需要替换为不同的元素或内容
            const replacement = `<div id='${idStr}' class='${classStr}'></div>`;
            return replacement;
          } catch (e) {
            return ``;
          }
        }
      );

      // const regex2 = /\$\$[^#]+##/g;
      const regex2 = /%%[^#]+##/g;
      const replacedString2 = replacedString.replace(
        regex2,
        (match: any, openTag: any, content: any, closeTag: any) => {
          echartsId.current += 1;
          // const matchText = match.match(/\$\$([^#]+)##/)
          const matchText = match.match(/%%([^#]+)##/);
          const textContent = matchText && matchText[1] ? matchText[1] : "";
          const splitArr = textContent.split("-");
          const codeType = splitArr[1];
          const codeId = splitArr[2];
          const resId = codeId || echartsId.current;
          const idStr = `chat-${codeType}-${chatItem.msgId}-${resId}-${echartsId.current}`;
          const classStr = `chat-${codeType}-block`;
          const replacement = `<div id='${idStr}' class='${classStr}'></div>`;
          arr.push({
            type: codeType,
            id: resId,
            domId: idStr,
            content: textContent,
            renderStr: replacement,
          });
          return replacement;
        }
      );
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      let renderText = "";
      const checkType = ["echarts", "topology"];
      if (mdRenderMode === "chart" && arr.length) {
        arr.forEach((i) => {
          if (checkType.includes(i.type)) {
            renderText += i.renderStr;
          }
        });
      }
      reslove({
        resultHtml: replacedString2,
        featureArr: arr,
      });
    });
  };

  const renderEcharts = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    let chartData = [];
    if (chartDataCxt && chartDataCxt[data.id]) {
      chartData = chartDataCxt[data.id];
    } else if (!data.id && JSON.stringify(chartDataCxt) !== "{}") {
      chartData = chartDataCxt;
    } else {
      chartData = [];
    }
    const fn = new Function(
      `var data = ${typeof chartData === "string" ? chartData : JSON.stringify(chartData)};${data.content}return option;`
    );
    let resOptions: any = {};
    try {
      resOptions = fn();
    } catch (e) {
      console.log("error==>", e);
    }
    console.log("renderEcharts data", data);
    console.log("renderEcharts featureData", featureData);
    console.log("renderEcharts chartDataCxt", chartDataCxt);
    console.log("renderEcharts chartDataCxt[data.id]", chartDataCxt[data.id]);
    console.log("renderEcharts chartData", chartData);
    console.log("renderEcharts resOptions", resOptions);
    console.log("renderEcharts fn", fn);
    resOptions = resOptions && typeof resOptions === "object" ? resOptions : {};
    render(
      // <ChatEcharts isPage={false} option={resOptions} />,
      <RenderDynamicComponent
        renderType={"ChatEcharts"}
        isPage={false}
        option={resOptions}
      />,
      targetDom
    );
  };

  const renderTable = async (
    data: FeatureItemType,
    tablePreview?: string,
    resultHtml?: string
  ) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    let tableData = {
      reportDataType: "table",
      reportData: [],
    };
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    if (chartDataCxt[data.id]) {
      const sourceData = chartDataCxt[data.id];
      if (typeof sourceData === "string") {
        tableData.reportData = JSON.parse(sourceData);
      } else {
        if (sourceData.reportDataType && sourceData.reportData) {
          tableData.reportDataType = sourceData.reportDataType;
          if (sourceData.reportDataType === "table") {
            tableData.reportData = sourceData.reportData[0]
              ? JSON.parse(sourceData.reportData[0])
              : {};
          } else {
            tableData.reportData = sourceData.reportData;
          }
        } else {
          tableData.reportData = sourceData;
        }
      }
    }
    const idStr = `chat-table-luckysheet-${featureData.msgId}-${data.id}`;
    let resMap: any = {};
    if (tablePreview) {
      // pass
    } else if (
      !featureData.tablePreview &&
      !coverImgMap?.[idStr] &&
      tableData.reportDataType === "table" &&
      Object.keys(tableData.reportData).length > 0
    ) {
      resMap = await addTask(
        featureData.msgId,
        idStr,
        tableData.reportData,
        qList
      );
    }
    let currentTablePreview =
      tablePreview ||
      featureData?.tablePreview ||
      resMap?.[idStr] ||
      coverImgMap?.[idStr];
    const cDom =
      tableData.reportDataType === "table" ? (
        // <ChatTable tableData={tableData.reportData} chatInfo={{
        //   msgId: featureData.msgId,
        //   dataId: data.id,
        // }} imgUrl={currentTablePreview} />
        <RenderDynamicComponent
          renderType={"ChatTable"}
          tableData={tableData.reportData}
          chatInfo={{
            msgId: featureData.msgId,
            dataId: data.id,
          }}
          imgUrl={currentTablePreview}
        />
      ) : (
        <div>当前报表不存在</div>
      );
    render(cDom, targetDom);
  };

  const renderRcTable = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    let tableData = {
      header: [],
      content: [],
    };
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    if (chartDataCxt && chartDataCxt[data.id]) {
      const sourceData = chartDataCxt[data.id];
      tableData = sourceData;
    }
    render(
      // <ChatRcTable
      // columns={tableData.header}
      // data={tableData.content}
      // ></ChatRcTable>,
      <RenderDynamicComponent
        renderType={"ChatRcTable"}
        columns={tableData.header}
        data={tableData.content}
      />,

      targetDom
    );
  };

  const renderTopology = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    const chartData =
      chartDataCxt && chartDataCxt[data.id] ? chartDataCxt[data.id] : [];
    render(
      // <ChatAnalysis
      // data={chartData}
      // theme={'light'}
      // ></ChatAnalysis>,
      <RenderDynamicComponent
        renderType={"ChatAnalysis"}
        data={chartData}
        theme={"light"}
      />,

      targetDom
    );
  };

  const renderAutoModelCalculate = (
    data: FeatureItemType,
    resultHtml?: string
  ) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    let type: ChatFeatureType = "none";
    let autoData: any = {};
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    if (chartDataCxt && chartDataCxt["autoModelCalculate"]) {
      type = "autoModelCalculate";
      const sourceData = chartDataCxt[type];
      autoData =
        typeof sourceData === "string" ? JSON.parse(sourceData) : sourceData;
    } else if (chartDataCxt && chartDataCxt["bottleneckAnalysis"]) {
      type = "bottleneckAnalysis";
      const sourceData = chartDataCxt[type];
      autoData =
        typeof sourceData === "string" ? JSON.parse(sourceData) : sourceData;
    }
    autoData.createTime = featureData.createTime;
    let redesignData = {
      type: type,
      data: autoData,
    };
    render(
      // <ChatRedesign
      // type={redesignData.type}
      // data={redesignData.data}
      // loading={!!isLoading}
      // ></ChatRedesign>,
      <RenderDynamicComponent
        renderType={"ChatRedesign"}
        type={redesignData.type}
        data={redesignData.data}
        loading={!!isLoading}
      />,

      targetDom
    );
  };

  const renderSuggested = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    const sourceData = parseString(chartDataCxt.content)
      ? parseString(`${chartDataCxt.content}`)
      : [];
    render(
      // <ChatSuggested
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }}
      //   quesList={sourceData}
      //   onCon={(str) => {
      //     handle(str);
      //   }}></ChatSuggested>,
      <RenderDynamicComponent
        renderType={"ChatSuggested"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        quesList={sourceData}
        onCon={(str) => {
          // handle(str);
          chatRef?.current?.handleChat(
            `${str}`
          );
        }}
      />,

      targetDom
    );
  };

  const renderContentSource = (data: FeatureItemType, resultHtml?: string) => {
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) {
      return;
    }
    let rsourceData: any = null;
    if (chartDataCxt[data.id]) {
      const sourceData = chartDataCxt[data.id];
      if (typeof sourceData === "string") {
        const resData = parseString(sourceData);
        if (resData) rsourceData = resData;
      } else {
        rsourceData = sourceData;
      }
    }
    render(
      // <ContentSource
      //   data={data}
      //   rsourceData={rsourceData}
      // ></ContentSource>,
      <RenderDynamicComponent
        renderType={"ContentSource"}
        data={data}
        rsourceData={rsourceData}
      />,

      targetDom
    );
  };

  const renderChatBI = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const sourceData = featureData?.messageBody?.chartData ?? {};
    render(
      // <ChatBI
      //   theme="light"
      //   // language={language}
      //   chartData={sourceData}
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }} ></ChatBI>,
      <RenderDynamicComponent
        renderType={"ChatBI"}
        theme="light"
        // language={language}
        chartData={sourceData}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
      />,

      targetDom
    );
  };

  const renderRecommendQues = (data: FeatureItemType, resultHtml?: string) => {
    const renderTag = (data: FeatureItemType) => {
      const targetDom = document.getElementById(data.domId);
      if (!targetDom) {
        return;
      }
      const view = document.createElement("view");
      let rsourceData: any = null;
      const featureData = chatItemRef.current;
      const chartDataCxt = featureData?.messageBody?.chartData ?? {};

      if (chartDataCxt[data.id]) {
        const sourceData = chartDataCxt[data.id];
        if (typeof sourceData === "string") {
          rsourceData = sourceData;
        } else {
          rsourceData = sourceData;
        }
      }
      render(
        // <RecommendQues
        //   rsourceData={rsourceData}
        // ></RecommendQues>,
        <RenderDynamicComponent
          renderType={"RecommendQues"}
          rsourceData={rsourceData}
        />,
        view
      );
      targetDom?.appendChild(view);
    };
    if (!renderDom) {
      let finalDom = (
        <div id={`chat-md-${id}`}>
          {resultHtml !== undefined && (
            <div
              className={styles["recommend-ques-wrapper"]}
              style={{ paddingBottom: 20 }}
              dangerouslySetInnerHTML={{
                __html: converter.makeHtml(resultHtml),
              }}
            ></div>
          )}
        </div>
      );
      setRenderDom(finalDom);
    }

    typedRef?.current?.destroy?.();
    setTimeout(() => {
      renderTag(data);
    }, 500);
  };

  const renderPlotly = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const chartDataCxt =
      featureData?.messageBody?.contents?.[0]?.metaData ?? {};
    let rsourceData: any = null;
    if (chartDataCxt[data.id]) {
      const sourceData = chartDataCxt[data.id];
      if (typeof sourceData === "string") {
        const resData = parseString(sourceData);
        if (resData) {
          rsourceData = resData;
        } else {
          rsourceData = sourceData;
        }
      } else {
        rsourceData = sourceData;
      }
    }
    render(
      // <ChatPlotly
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }}
      //   language={language}
      //   rsourceData={rsourceData}
      // ></ChatPlotly>,
      <RenderDynamicComponent
        renderType={"ChatPlotly"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        language={language}
        rsourceData={rsourceData}
      />,
      targetDom
    );
  };

  const renderThink = (data: FeatureItemType, resultHtml?: string) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    render(
      // <ChatThink
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }}
      //   featureData={featureData}
      //   language={language}
      //   content={data.content}
      // />,
      <RenderDynamicComponent
        renderType={"ChatThink"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        featureData={featureData}
        language={language}
        content={data.content}
      />,
      targetDom
    );
  };

  const renderPidData = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    const chartData =
      chartDataCxt && chartDataCxt[data.id] ? chartDataCxt[data.id] : [];

    render(
      // <PidDataTrendEcharts
      //   theme={'light'}
      //   chartData={chartData}
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }}
      // // onRender={onRender}
      // />
      // ,
      <RenderDynamicComponent
        renderType={"PidDataTrendEcharts"}
        theme={"light"}
        chartData={chartData}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
      // onRender={onRender}
      />,
      targetDom
    );
  };

  const renderPidExecute = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;

    const chartDataCxt = featureData?.messageBody?.chartData ?? {};
    const chartData =
      chartDataCxt && chartDataCxt[data.id] ? chartDataCxt[data.id] : [];
    render(
      // <PidExecuteTrendEcharts
      //   theme={'light'}
      //   chartData={chartData}
      //   chatInfo={{
      //     msgId: featureData.msgId,
      //     dataId: data.id,
      //   }}
      // />
      // ,
      <RenderDynamicComponent
        renderType={"PidExecuteTrendEcharts"}
        theme={"light"}
        chartData={chartData}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
      />,
      targetDom
    );
  };

  const renderPathSuggest = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;

    const res: any = featureData?.messageBody?.contents?.[0]?.metaData?.res
      ? JSON.parse(`${featureData?.messageBody?.contents?.[0]?.metaData?.res}`)
      : null;
    const { success, content = {}, suggestion = "" } = res || {};
    console.log("renderPathSuggest res", res);

    // let tagName = content?.constraint?.[0]?.desc ?? "";
    let match = suggestion.match(/(\d+#裂解炉)/); // 匹配 "数字#裂解炉"
    let targetName = match ? match[1] : "";

    // 操作路径规划 额外操作： 1切换 场景  2. 保存数据
    if (viewContent.id === featureData?.id) {
      if (success) {
        // 1. 切换为 操作路径规划
        setCurrentKey("path");
        // 2. 保存数据
        setPathJson(content);

        if (targetName) {
          setCurrentPathDevice(targetName);
        }
      }
    }
    render(
      <RenderDynamicComponent
        renderType={"Suggestions"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        suggestion={[
          {
            text: suggestion,
            target: false,
          },
        ]}
      // onCon={(str) => {
      //   handle(str);
      // }}
      />,

      targetDom
    );
  };

  const renderAw = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;
    const res: any = featureData?.messageBody?.contents?.[0]?.metaData
      ?.resource_info
      ? JSON.parse(
        `${featureData?.messageBody?.contents?.[0]?.metaData?.resource_info}`
      )
      : null;
    const { resource_list = [], suggestion = "", reason = "" } = res || {};
    console.log("renderAw featureData", featureData);
    console.log("renderAw res", res);
    let resourceItem = resource_list?.[0]?.id ?? "";
    let cSuggestion: any[] = [
      {
        text: reason,
        target: false,
        label: "",
        type: "reason",
      },
      {
        text: suggestion,
        target: false,
        label: "",
      },
    ];
    if (resourceItem.includes("#裂解炉乙烯收率")) {
      let label = resourceItem.split("乙烯收率")?.[0] ?? "";
      cSuggestion = [
        {
          text: reason,
          target: false,
          label: "",
          type: "reason",
        },
        {
          text: suggestion,
          target: true,
          label: label,
        },
      ];
    }
    // 异常预警规划 额外操作： 1切换 场景  2. 保存数据
    console.log("renderAw viewContent", viewContent);
    console.log("renderAw viewContent data", data);
    if (viewContent.id === featureData?.id) {
      // 1. 切换为 操作路径规划
      setCurrentKey("anomaly");
      // 2. 保存数据
      setAnomalyJson(res);
    }

    render(
      <RenderDynamicComponent
        renderType={"Suggestions"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        suggestion={cSuggestion}
        onCon={(str) => {
          chatRef?.current?.handleChat(
            `针对${str}，在当前工况下如何调整操作变量从而提高裂解炉乙烯收率？`
          );
          // handle(
          //   `针对${str}，在当前工况下如何调整操作变量从而提高裂解炉乙烯收率？`
          // );
        }}
      />,

      targetDom
    );
  };

  const rendeOoops = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;

    const res: any = featureData?.messageBody?.contents?.[0]?.metaData?.res
      ? JSON.parse(`${featureData?.messageBody?.contents?.[0]?.metaData?.res}`)
      : null;
    const { success, content = {}, suggestion = [] } = res || {};
    console.log("rendeOoops featureData", featureData);
    console.log("rendeOoops res", res);

    // 操作路径规划 额外操作： 1切换 场景  2. 保存数据
    if (viewContent.id === featureData?.id) {
      if (success) {
        // 1. 切换为 操作路径规划
        setCurrentKey("param");
        // 2. 保存数据
        setParamJson(content);
      }
    }
    render(
      <RenderDynamicComponent
        renderType={"Suggestions"}
        chatInfo={{
          msgId: featureData.msgId,
          dataId: data.id,
        }}
        suggestion={[suggestion]}
        onCon={(str) => {
          chatRef?.current?.handleChat(
            `${str}投炉升温过程如何优化COT操作路径，在保证安全平稳的前提下更快速的调整到位。`
          );
          // handle(
          //   `${str}投炉升温过程如何优化COT操作路径，在保证安全平稳的前提下更快速的调整到位。`
          // );
        }}
      />,

      targetDom
    );
  };

  const renderOoopTable = (data: FeatureItemType) => {
    const targetDom = document.getElementById(data.domId);
    if (!targetDom) return;
    const featureData = chatItemRef.current;

    const res: any = featureData?.messageBody?.contents?.[0]?.metaData?.res
      ? JSON.parse(`${featureData?.messageBody?.contents?.[0]?.metaData?.res}`)
      : null;
    console.log("renderOoopTable featureData", featureData);
    console.log("renderOoopTable res", res);
    const tableData = res?.[data.id] ?? {};
    if (tableData?.data) {
      render(
        <RenderDynamicComponent
          renderType={"OoopTable"}
          chatInfo={{
            msgId: featureData.msgId,
            dataId: data.id,
          }}
          data={tableData}
        // onCon={(str) => {
        //   handle(str);
        // }}
        />,
        targetDom
      );
    }
  };
  // TODO: 后续优化 支持 额外 type
  const renderFeature = (props: {
    tablePreview?: string;
    resultHtml?: string;
  }) => {
    const { tablePreview, resultHtml } = props;
    console.log("featureRef item", featureRef.current);
    featureRef.current.forEach((item) => {
      if (item.type === "echarts") {
        // 1#电解槽槽温未来趋势怎么变化
        renderEcharts(item, resultHtml);
      } else if (item.type === "table") {
        // 查询一下2024年3月13日化工氯碱装置生产日报表
        renderTable(item, tablePreview, resultHtml);
      }
      // TODO: 需要验证
      else if (item.type === "rctable") {
        renderRcTable(item, resultHtml);
      } else if (item.type === "topology") {
        // 这个月氯碱一厂氢气产量的环比变化是多少
        renderTopology(item, resultHtml);
      }
      // else if (['autoModelCalculate', 'bottleneckAnalysis', 'deviceReport'].includes(item.type)) {
      else if (
        ["autoModelCalculate", "bottleneckAnalysis"].includes(item.type)
      ) {
        renderAutoModelCalculate(item, resultHtml);
      } else if (item.type === "suggested") {
        renderSuggested(item, resultHtml);
      } else if (item.type === "contentSource") {
        renderContentSource(item, resultHtml);
      } else if (item.type === "chatBI") {
        renderChatBI(item);
      } else if (item.type === "recommendQues") {
        renderRecommendQues(item, resultHtml);
      } else if (item.type === "plotly") {
        renderPlotly(item, resultHtml);
      } else if (item.type === "think") {
        renderThink(item, resultHtml);
      }
      // else if (item.type === 'exam') {
      //   renderExam(item, resultHtml)
      // }
      else if (item.type === "pidDataTrend") {
        renderPidData(item);
      } else if (item.type === "pidExecuteTrend") {
        renderPidExecute(item);
      } else if (item.type === "aw") {
        // 输出 异常预警
        renderAw(item);
      } else if (item.type === "ooops") {
        // 输出 操作参数规划 建议
        rendeOoops(item);
      } else if (item.type === "oooph") {
        // 输出 操作路径规划 建议
        renderPathSuggest(item);
      } else if (item.type === "ooopt") {
        // 输出 操作 表格
        renderOoopTable(item);
      }
    });
  };

  const renderFeatureCb = useCallback(
    debounce((tablePreview?: string, resultHtml?: string) => {
      if (featureRef.current.length > 0) {
        renderFeature({ tablePreview, resultHtml });
      }
    }, 1000),
    []
  );

  const renderContentMd = (props: IRenderContentMdProps) => {
    const { str, tablePreview = "", destroyType = true } = props;
    parseMd(str).then((res) => {
      const rootDom = document.getElementById(`chat-md-${id}`);
      if (rootDom) {
        rootDom.innerHTML =
          res.resultHtml !== undefined
            ? res.resultHtml
            : converter.makeHtml(
              viewContent.id === msgId ? "" : renderNoBkText
            );
      }
      if (res.featureArr.length) {
        featureRef.current = res.featureArr;
        if (destroyType) {
          typedRef?.current?.destroy?.();
        }
        renderFeatureCb(tablePreview, res.resultHtml);
      }
    });
  };

  // ! 长按 弹窗
  // useLongPress((e) => toHandleLongPress(e), longPressRef, {
  //   delay: 1000,
  // })

  // ? 这边不需要,不然在 生产环境浏览器会导致 rendertext影响回答内容
  useEffect(() => {
    if (role === CHAT_ROLE.view && isLoading) {
      renderMd(true);
    }
  }, [role, isLoading]);

  const { showText } = useLoadText(
    content,
    {
      // loading: !!loading && !content.includes('supgptcode-'),
      loading: false,
    },
    {
      onLoad: () => {
        setRecommendationLoad(true);
      },
      onEnd: (load) => {
        setRecommendationLoad(false);
        onRender && onRender(true);

        // 这边需要 修改 全局 的场景 如
        // 异常预警 操作参数优化 操作路径优化
        // TODO:
      },
    }
  );

  const scrollLoadingChat = useCallback(
    throttle((isForce?: boolean) => {
      let canLoad = false;
      if (isLoading) {
        if (loading) {
          canLoad = true;
        }
      } else {
        if (loading || isForce) {
          canLoad = true;
        }
      }
      if (canLoad) {
        setTimeout(() => {
          updateScrollTop();
        }, 1000);
      }
      if (anwserRef.current && (loading || isForce)) {
        anwserRef.current.scrollIntoView({ block: "end" });
      }
      // if (anwserRef.current && canLoad) {
      //   console.log('scrollLoadingChat ==> ');
      //   anwserRef.current.scrollIntoView({ block: 'end' });
      // }
    }, 1000),
    [loading, isLoading]
  );
  const onRender = (isForce?: boolean) => {
    scrollLoadingChat(isForce);
  };

  useEffect(() => {
    if (role === CHAT_ROLE.assistant) {
      renderContentMd({ str: showText, tablePreview });
    }
  }, [id, showText, useCompare(tablePreview), role]);

  useEffect(() => {
    return () => {
      if (typedRef.current) {
        typedRef.current?.destroy?.();
      }
    };
  }, []);
  return (
    <div key={key} className={cName(styles["chat"])}>
      {who === CHAT_ROLE.user ? (
        <div>
          <div className={styles["message-wrapper"]}>
            <div className={styles["place"]}></div>
            <div className={cName(styles["message_user"])}>{content}</div>
          </div>
        </div>
      ) : (
        <div>
          <div className={styles["chat-wrapper"]}>
            <div ref={anwserRef} className={styles["message-wrapper"]}>
              {
                // 初始化聊天 提示样式
                isInitChat ? (
                  <div className={styles["init-chat-wrapper"]}>
                    <div className={styles["head"]}>
                      <div className={styles["left"]}>
                        <IconFont
                          className={styles["icon"]}
                          name={tptLift}
                          size="1.5rem"
                        />
                      </div>
                      <div className={styles["title"]}>您好</div>
                    </div>
                    {qList?.length === 1 && (
                      <div className={styles["desc-wrapper"]}>
                        <div className={styles["desc"]}>你可以问我：</div>

                        <div>
                          <div
                            className="ques-title-opera"
                            onClick={() => {
                              resetRecommend(msgId);
                            }}
                          >
                            <RefreshOutlined></RefreshOutlined>
                            <span>换一批</span>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* 第一次才展示默认推荐问题 */}
                    {qList?.length === 1 && (
                      <div className={styles["opts"]}>
                        <RecommendationProblem
                          initMode={true}
                          recommended={recommended}
                        />
                      </div>
                    )}
                  </div>
                ) : (
                  <div className={styles["message-resp"]}>
                    <Avatar
                      className={styles["message-avatar"]}
                      shape="square"
                      src={tptLift}
                    />
                    <div className={styles["message-body"]}>
                      <div
                        className={cName(
                          styles["message"],
                          styles["message_ai"]
                        )}
                      >
                        <div
                        // ref={longPressRef}
                        >
                          <ChatThink
                            thinks={thinks}
                            loading={loading}
                          ></ChatThink>
                          <div ref={el} id={`chat-md-${id}`}></div>
                        </div>
                        {/* // ! 不是初始化的回答 + 有回答  */}
                        {!!msgId && role !== CHAT_ROLE.view && (
                          <MsgQuickAction
                            msgContent={chatItem}
                            handleActionClick={showActionLog}
                            handleActionFileList={showActionFile}
                            handleFeedBackDownClick={handleFeedBackDownClick}
                          />
                        )}
                      </div>

                      {!!resourceList.length &&
                        showActionFileList.includes(msgId) && (
                          <div className={styles["answer-actions"]}>
                            {resourceList.map((item, index) => {
                              return (
                                <div
                                  className={styles["answer-actions-item"]}
                                  key={index}
                                >
                                  <div
                                    className={styles["answer-actions-item-t"]}
                                  >
                                    {index + 1}.
                                  </div>
                                  <div
                                    className={styles["answer-actions-item-c"]}
                                  >
                                    {item.name}
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        )}

                      {/* 流程日志 */}
                      {actions &&
                        !!actions.length &&
                        showActionLogList.includes(msgId) && (
                          <div className={styles["answer-actions"]}>
                            {actions.map((item, index) => {
                              return (
                                <div
                                  className={styles["answer-actions-item"]}
                                  key={index}
                                >
                                  <div
                                    className={styles["answer-actions-item-t"]}
                                  >
                                    {item.actionName}:
                                  </div>
                                  <div
                                    className={styles["answer-actions-item-c"]}
                                  >
                                    {item.actionContent}
                                  </div>
                                </div>
                              );
                            })}
                          </div>
                        )}
                    </div>
                  </div>
                )
              }
            </div>
          </div>
          {/* 推荐问题 */}
          {showRecommendation && (
            <RecommendationProblem recommended={recommended} />
          )}
        </div>
      )}
    </div>
  );
}

export default memo(ChatItem);
